/**
 * http 服务，对 url 监听， 返回对应的 html 文件或者  404
 * html 文件可能存在很多静态资源，例如 css js 文件，也需要考虑
 */
import http from "node:http";
import fs from "node:fs";
import url from "node:url"
import path from 'node:path';

const __dirname = path.dirname(url.fileURLToPath(import.meta.url))


const extToType = {
  ".js": "text/javascript",
  ".css": "text/css",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".png": "image/png"
}



const isExitFile = (file_path) => {
  // console.log("file_path", file_path);
  try {
    const stat = fs.statSync(file_path);
    return stat.isFile();
  } catch (error) {
    return false;
  }
}



const server = http.createServer((req, res) => {
  let file_path;
  const routePath = url.parse(req.url).pathname
  const ext = path.extname(routePath);


  if (ext) {
    // 有后缀默认
    file_path = path.join(process.cwd(), routePath);
  } else {
    // 无后缀默认 .html, 默认首路由返回 index.html
    file_path = path.join(process.cwd(), routePath === "/" ? "/index.html" : routePath + ".html");
  }

  const isExit = isExitFile(file_path);

  if (!isExit) {
    res.writeHead(404, { "content-type": "text/plain" })
    res.end();
  } else {
    // 存在， fs.readFile 有内存耗尽的风险， 使用流传输

    const readStream = fs.createReadStream(file_path, "utf-8")
    const mime = extToType[ext] ?? "text/html";

    // console.log("传输数据。。。", ext, mime)
    res.writeHead(200, { 'Content-Type': mime });
    readStream.pipe(res);
    // res.end();
  }

})

server.listen(3000, () => {
  console.log("服务启动, prot:", 3000)
});
